package service

import (
	"encoding/json"
	"errors"
	"fmt"
	"git.inedcn.com/ined/cmn"
	"math/rand"
	constant "rongyy/src/constants"
	"rongyy/src/helper"
	"rongyy/src/middlewares"
	"rongyy/src/models"
	"strconv"
	"time"
)

type PatientCardService struct {
}

// FindPatientCard
//
//	@Description: 查询卡
//	@receiver pc
//	@param req
//	@return *models.Resp3013
//	@return error
func (pc *PatientCardService) FindPatientCard(req *models.Req3013Params) (*models.Resp3013, error) {
	data, err := (&HisService{}).FindPatientCard(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

// SavePatientCard
//
//	@Description: 发卡
//	@receiver pc
//	@param req
//	@return *models.Resp3014
//	@return error
func (pc *PatientCardService) SavePatientCard(req *models.Req3014Params) (*models.Resp3014, error) {
	data, err := (&HisService{}).SavePatientCard(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) GetPatInfo(req *models.Req3300Params) (*models.Resp3300, error) {
	data, err := (&HisService{}).GetPatInfo(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) UpdatePatInfo(req *models.CardReqParams) error {
	_, has, err := (&models.CardModel{}).FindByPatientId(req.PatientId)
	if !has {
		return errors.New("用户不存在")
	}
	if err != nil {
		middlewares.Logger.Println("UpdatePatInfo FindByPatientId failed ", err)
		return err
	}

	cm := &models.CardModel{}
	err = cm.UpdateNameTel(req.PatientId, req.TelephoneNo, req.PatientName)
	if err != nil {
		middlewares.Logger.Println("UpdatePatInfo sql failed ", err)
		return err
	}
	return nil
}

func (pc *PatientCardService) GetOccupations() (*models.RespOccupation, error) {
	data, err := (&HisService{}).GetOccupations()
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) GetHisBills(req *models.Req6001Params) (*models.Resp6001, error) {
	data, err := (&HisService{}).GetHisBills(req)
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) GetReportIdsByAdm(admNo string) (*models.Resp0036, error) {
	data, err := (&HisService{}).GetReportIdsByAdm(admNo)
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) GetReportsById(reportId string) (*models.Resp0037, error) {
	data, err := (&HisService{}).GetReportsById(reportId)
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return nil, err
	}
	return data, nil
}

func (pc *PatientCardService) Unbind(req *models.ReqUnbind) error {
	user, has, err := (&models.UserModel{}).FindById(req.Wxid)
	if !has {
		return errors.New("无对应用户信息")
	}
	card, has, err := (&models.CardModel{}).GetPatientBySourceId(req.SourceId)
	if !has {
		return errors.New("无对应卡信息")
	}
	err = (&models.CardModel{}).UnbindCard(user.Unionid, card.Id)
	if err != nil {
		middlewares.Logger.Println("Unmarshal GetHisBills failed ", err)
		return err
	}
	return nil
}

// Create
//
//	@Description: 建电子健康卡
//	@receiver pc
//	@param req
//	@return error
func (pc *PatientCardService) CreateCard(req *models.EcardCreateReq) error {
	//1.查询绑卡数是否达到上线
	_, total, err := (&models.UserModel{}).FindCardsByUnionid(req.Unionid)
	if err != nil {
		middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", err)
		return err
	}
	if total == 5 {
		return fmt.Errorf("绑卡数已达到上限")
	}
	//2.判断是否已经建卡
	card, has, err := (&models.CardModel{}).FindCardByIDM(req.IdNo)
	middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", card)
	if err != nil {
		middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", err)
		return err
	}
	//如果存在，直接绑卡
	//1. 查询是否已绑卡
	_, hasBind, err := (&models.CardModel{}).FindBindCardInfo(card.Id, req.Unionid)
	if hasBind {
		return fmt.Errorf("此卡已绑定在当前用户")
	}
	if has && !hasBind {
		reqCardBind := &models.CardBindModel{
			Unionid:   req.Unionid,
			PatientId: card.Id,
			Status:    1,
		}
		err = (&models.CardModel{}).BindCard(reqCardBind)
		return err
	}

	// 护照建卡
	if req.IdType != "01" && req.IdType != "02" {
		reqFindCard := &models.Req3013Params{
			IDType:      req.IdType,
			IDNo:        req.IdNo,
			PatientName: req.PatientName,
			PatientCard: "",
		}
		respFindPC, err := (&HisService{}).FindPatientCard(reqFindCard)
		if err != nil {
			middlewares.Logger.Println("CreateCard 护照建卡 failed ", err)
			return err
		}
		if respFindPC.ResultCode == "1" {
			sex := "1"
			if req.Sex == "女" {
				sex = "2"
			}
			sexint, _ := strconv.Atoi(sex)
			cmi := &models.CardModel{
				Age:        req.Age,
				CardNo:     "",
				EcardNo:    respFindPC.PatientCard,
				Empi:       "",
				IdNo:       req.IdNo,
				Mobile:     req.Mobile,
				Nation:     req.Nation,
				RealName:   req.PatientName,
				Sex:        sexint,
				SourceId:   respFindPC.PatientID,
				Occupation: req.Job,
				CreatedAt:  cmn.JsonTime{},
				UpdatedAt:  cmn.JsonTime{},
			}
			card, err = (&models.CardModel{}).Insert(cmi)
			cardbindreq := &models.CardBindModel{
				Unionid:   req.Unionid,
				PatientId: card.Id,
				Status:    1,
			}
			err = (&models.CardModel{}).BindCard(cardbindreq)
			return nil
		} else if
		// 卡在his存在，直接绑
		respFindPC.ResultCode == "-51" && respFindPC.ResultContent == "已存在同种类型的卡,不能发卡" {
			sex := "1"
			if req.Sex == "女" {
				sex = "2"
			}
			sexint, err := strconv.Atoi(sex)
			if err != nil {
				middlewares.Logger.Println("CreateCard sexint failed ", err)
				return err
			}
			cmi := &models.CardModel{
				Age:        req.Age,
				CardNo:     "",
				EcardNo:    respFindPC.PatientCard,
				Empi:       "",
				IdNo:       req.IdNo,
				Mobile:     req.Mobile,
				Nation:     req.Nation,
				RealName:   req.PatientName,
				Sex:        sexint,
				SourceId:   respFindPC.PatientID,
				Occupation: req.Job,
				CreatedAt:  cmn.JsonTime{},
				UpdatedAt:  cmn.JsonTime{},
			}
			cardN, err := (&models.CardModel{}).Insert(cmi)
			cardbindreq := &models.CardBindModel{
				Unionid:   req.Unionid,
				PatientId: cardN.Id,
				Status:    1,
			}
			err = (&models.CardModel{}).BindCard(cardbindreq)
			return nil
		} else {
			return fmt.Errorf(respFindPC.ResultContent + ", 请联系工作人员")
		}
	}
	// 护照建卡完毕

	//// 查询是否有电子健康卡
	//reqFindCard := &models.Req3013Params{
	//	IDType:      req.IdType,
	//	IDNo:        req.IdNo,
	//	PatientName: req.PatientName,
	//	PatientCard: "",
	//}
	//respFindECard, err := (&HisService{}).FindPatientCard(reqFindCard)

	secret, err := helper.Sm2Encrypto(constant.CardCenterAppSecret, constant.CardCenterPubKey)
	fmt.Println(secret)
	type BizContent struct {
		Secret string `json:"secret"`
	}
	biz := &BizContent{Secret: secret}
	ca := &models.Ca{
		EncType:    "SM4",
		Method:     "token",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: *biz,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	token, err := (&ECardService{}).GetToken(ca)
	// 不存在，就走卡管中心，建卡
	sm4Info := &models.Sm4Info{
		AppMode:       "6",
		IdType:        "01",
		IdNo:          req.IdNo,
		Klx:           "1",
		Name:          req.PatientName,
		Birthday:      req.Dob,
		Cellphone:     req.Mobile,
		Citizenship:   "1",
		EthnicityCode: "01",
		Gender:        "",
		HjAddress:     "地址2",
		NativePlace:   "地址3",
		Sbkh:          "333333",
		Telephone:     req.Mobile,
		TerminalType:  "1",
		Unit:          "地址3",
		Ylfyzffs:      "01",
		Zydm:          "8",
		Rzfs:          "05",
	}
	reqSm4 := &models.Sm4EncryptReq{
		Info:  *sm4Info,
		Token: token,
	}
	sm4resp, err := helper.Sm4Encrypto(reqSm4)
	encryToken, err := helper.Sm2Encrypto(token, constant.CardCenterPubKey)
	ecardPa := &models.EcardPa{
		EncType:    "sm4",
		Method:     "regquery",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: sm4resp,
		Digest:     encryToken,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	middlewares.Logger.Println("卡管中心入参------", ecardPa)
	res, err := (&ECardService{}).GetEcard(ecardPa)
	middlewares.Logger.Println("卡管中心出参------", res)
	// 如果卡管中心报错，直接院内建卡
	if err != nil {
		middlewares.Logger.Println("卡管中心报错------", err.Error())
		fmt.Println("如果卡管中心报错，直接院内建卡")
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	EcardInfo := res.RespData.BizContent
	fmt.Println("EcardInfo====", EcardInfo)

	Sm4DecryptReq := &models.Sm4DecryptReq{
		Token: token,
		Biz:   EcardInfo,
	}
	sm4DC, err := helper.Sm4Decrypto(Sm4DecryptReq)

	type Sm4DCModel struct {
		EcContent string `json:"ecContent"`
		Vuid      string `json:"vuid"`
		Empi      string `json:"empi"`
	}
	sss := &Sm4DCModel{}
	err = json.Unmarshal([]byte(sm4DC.RespData), sss)
	middlewares.Logger.Println("FindPatientCard====", sss)
	//检查卡是否在his系统
	reqFindCard := &models.Req3013Params{
		IDType:      "01",
		IDNo:        req.IdNo,
		PatientName: req.PatientName,
		PatientCard: sss.Vuid,
	}
	middlewares.Logger.Println("建卡建卡 卡管中心号码====", sss)
	middlewares.Logger.Println("建卡建卡 卡管中心号码====", sss.Vuid)
	respFindPC, err := (&HisService{}).FindPatientCard(reqFindCard)
	middlewares.Logger.Println("FindPatientCard====", respFindPC)
	if respFindPC.ResultCode != "0" && respFindPC.ResultContent != "已存在同种类型的卡,不能发卡" && respFindPC.ResultContent != "此卡号已建卡." {
		return fmt.Errorf(respFindPC.ResultContent)
	}

	// 卡在his存在，直接绑
	if respFindPC.ResultCode == "-51" && respFindPC.ResultContent == "已存在同种类型的卡,不能发卡" {
		sex := "1"
		if req.Sex == "女" {
			sex = "2"
		}
		sexint, err := strconv.Atoi(sex)
		if err != nil {
			middlewares.Logger.Println("CreateCard sexint failed ", err)
			return err
		}
		cmi := &models.CardModel{
			Age:        req.Age,
			CardNo:     "",
			EcardNo:    respFindPC.PatientCard,
			Empi:       "",
			IdNo:       req.IdNo,
			Mobile:     req.Mobile,
			Nation:     req.Nation,
			RealName:   req.PatientName,
			Sex:        sexint,
			SourceId:   respFindPC.PatientID,
			Occupation: req.Job,
			CreatedAt:  cmn.JsonTime{},
			UpdatedAt:  cmn.JsonTime{},
		}
		cardN, err := (&models.CardModel{}).Insert(cmi)
		cardbindreq := &models.CardBindModel{
			Unionid:   req.Unionid,
			PatientId: cardN.Id,
			Status:    1,
		}
		err = (&models.CardModel{}).BindCard(cardbindreq)
		return nil
	}

	if len(sss.Vuid) != 64 {
		middlewares.Logger.Println("绑卡失败（电子健康卡数据错误）====", sss)
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	formatDob := req.Dob[0:4] + "-" + req.Dob[4:6] + "-" + req.Dob[6:]
	fmt.Println("formatDob------------", formatDob)
	sex := "1"
	if req.Sex == "女" {
		sex = "2"
	}
	bindCardReq := &models.Req3014Params{
		IDType:        "01",
		IDNo:          req.IdNo,
		PatientName:   req.PatientName,
		PatientCard:   sss.Vuid,
		Sex:           sex,
		DOB:           formatDob,
		Mobile:        req.Mobile,
		MaritalStatus: req.MaritalStatus,
		Address:       req.Address,
		ContactTelNo:  req.ContactTelNo,
		ContactName:   req.ContactName,
		ContactIDNo:   req.ContactIDNo,
		Nation:        req.Nation,
		Occupation:    req.Job,
	}
	bindRes, err := (&HisService{}).SavePatientCard(bindCardReq)
	fmt.Println("bindRes:=======", bindRes)
	patientId := ""
	if bindRes.ResultCode == "0" || bindRes.ResultCode == "-50" || bindRes.ResultCode == "-51" {
		patientId = bindRes.PatientId
	} else {
		return fmt.Errorf("建卡失败")
	}
	sexint, err := strconv.Atoi(sex)
	fmt.Println("sexint----------", sexint)
	cmi := &models.CardModel{
		Age:        req.Age,
		CardNo:     "",
		EcardNo:    sss.Vuid,
		Empi:       sss.Empi,
		IdNo:       req.IdNo,
		Mobile:     req.Mobile,
		Nation:     req.Nation,
		RealName:   req.PatientName,
		Sex:        sexint,
		SourceId:   patientId,
		Occupation: req.Job,
		CreatedAt:  cmn.JsonTime{},
		UpdatedAt:  cmn.JsonTime{},
	}
	card, err = (&models.CardModel{}).Insert(cmi)
	cardbindreq := &models.CardBindModel{
		Unionid:   req.Unionid,
		PatientId: card.Id,
		Status:    1,
	}
	fmt.Println("cardbindreq----------", cardbindreq)
	err = (&models.CardModel{}).BindCard(cardbindreq)
	return nil
}

func (pc *PatientCardService) UpgradeCard(req *models.CardReqParams) error {
	pid := req.PatientId
	_, has, err := (&models.CardModel{}).GetPatientBySourceId(pid)
	if !has {
		fmt.Errorf("患者信息不存在, 请直接绑卡")
	}
	reqhis := &models.Req3300Params{
		PatientId: req.PatientId,
	}
	resHis, err := (&HisService{}).GetPatInfo(reqhis)
	if err != nil {
		middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
		return err
	}
	if resHis.ResultCode == "0" && len(resHis.PatInfos[0].PatientCard) > 0 {
		err = (&models.CardModel{}).UpdateEcardByPid(resHis.PatInfos[0].PatientCard, pid)
		if err != nil {
			middlewares.Logger.Println("Unmarshal resp3013 failed ", err)
			return err
		}
		return nil
	}

	return fmt.Errorf("请直接绑卡")
}

// 建院内卡
func (pc *PatientCardService) CreateHospCard(req *models.EcardCreateReq) error {
	reqFindCard := &models.Req3013Params{
		IDType:       req.IdType,
		IDNo:         req.IdNo,
		PatientName:  req.PatientName,
		PatientCard:  "",
		CardTypeCode: "03",
	}
	respFindPC, err := (&HisService{}).FindPatientCard(reqFindCard)
	fmt.Println("++++++++++++++++++++====", respFindPC)
	if err != nil {

	}
	if respFindPC.ResultCode != "0" && respFindPC.ResultContent != "已存在同种类型的卡,不能发卡" {
		return fmt.Errorf(respFindPC.ResultContent)
	}
	// 卡在his存在，直接绑
	if respFindPC.ResultCode == "-51" && respFindPC.ResultContent == "已存在同种类型的卡,不能发卡" {
		sex := "1"
		if req.Sex == "女" {
			sex = "2"
		}
		sexint, err := strconv.Atoi(sex)
		if err != nil {
			middlewares.Logger.Println("CreateCard sexint failed ", err)
			return err
		}
		cmi := &models.CardModel{
			Age:        req.Age,
			CardNo:     "",
			EcardNo:    respFindPC.PatientCard,
			Empi:       "",
			IdNo:       req.IdNo,
			Mobile:     req.Mobile,
			Nation:     req.Nation,
			RealName:   req.PatientName,
			Sex:        sexint,
			SourceId:   respFindPC.PatientID,
			Occupation: req.Job,
			CreatedAt:  cmn.JsonTime{},
			UpdatedAt:  cmn.JsonTime{},
		}
		card, err := (&models.CardModel{}).Insert(cmi)
		cardbindreq := &models.CardBindModel{
			Unionid:   req.Unionid,
			PatientId: card.Id,
			Status:    1,
		}
		err = (&models.CardModel{}).BindCard(cardbindreq)
		return nil
	}

	// his无卡, 建院内卡
	formatDob := req.Dob[0:4] + "-" + req.Dob[4:6] + "-" + req.Dob[6:]
	sex := "1"
	if req.Sex == "女" {
		sex = "2"
	}
	// 生成随机卡号
	rand.Seed(time.Now().UnixNano()) // 初始化随机种子

	// 生成15位随机数，前13位是随机数，后两位是'4'和'7'
	number := rand.Intn(999999999999999)      // 生成15位以内的随机数
	numberStr := fmt.Sprintf("%015d", number) // 格式化为15位数，不足部分用0填充

	PatientCard := numberStr

	bindCardReq := &models.Req3014Params{
		IDType:        "01",
		IDNo:          req.IdNo,
		PatientName:   req.PatientName,
		PatientCard:   PatientCard,
		Sex:           sex,
		DOB:           formatDob,
		Mobile:        req.Mobile,
		MaritalStatus: req.MaritalStatus,
		Address:       req.Address,
		ContactTelNo:  req.ContactTelNo,
		ContactName:   req.ContactName,
		ContactIDNo:   req.ContactIDNo,
		CardTypeCode:  "03",
		Nation:        req.Nation,
		Occupation:    req.Job,
	}
	fmt.Println("bindCardReq===", bindCardReq)
	bindRes, err := (&HisService{}).SavePatientCard(bindCardReq)
	patientId := ""
	if bindRes.ResultCode == "0" || bindRes.ResultCode == "-50" || bindRes.ResultCode == "-51" {
		patientId = bindRes.PatientId
	} else {
		return fmt.Errorf("建卡失败(内部)")
	}
	sexint, err := strconv.Atoi(sex)
	cmi := &models.CardModel{
		Age:        req.Age,
		CardNo:     "",
		EcardNo:    PatientCard,
		Empi:       "",
		IdNo:       req.IdNo,
		Mobile:     req.Mobile,
		Nation:     req.Nation,
		RealName:   req.PatientName,
		Sex:        sexint,
		SourceId:   patientId,
		Occupation: req.Job,
		CreatedAt:  cmn.JsonTime{},
		UpdatedAt:  cmn.JsonTime{},
	}
	card, err := (&models.CardModel{}).Insert(cmi)
	cardbindreq := &models.CardBindModel{
		Unionid:   req.Unionid,
		PatientId: card.Id,
		Status:    1,
	}
	err = (&models.CardModel{}).BindCard(cardbindreq)
	return nil
}

// Create
//
//	@Description: 建电子健康卡
//	@receiver pc
//	@param req
//	@return error
func (pc *PatientCardService) GetEcardCenterInfo(req *models.EcardCreateReq) error {
	//1.查询绑卡数是否达到上线
	_, total, err := (&models.UserModel{}).FindCardsByUnionid(req.Unionid)
	if err != nil {
		middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", err)
		return err
	}
	if total == 5 {
		return fmt.Errorf("绑卡数已达到上限")
	}

	secret, err := helper.Sm2Encrypto(constant.CardCenterAppSecret, constant.CardCenterPubKey)
	fmt.Println(secret)
	type BizContent struct {
		Secret string `json:"secret"`
	}
	biz := &BizContent{Secret: secret}
	ca := &models.Ca{
		EncType:    "SM4",
		Method:     "token",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: *biz,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	token, err := (&ECardService{}).GetToken(ca)
	// 不存在，就走卡管中心，建卡
	sm4Info := &models.Sm4Info{
		IdType: "",
		IdNo:   "",
		Rzfs:   "05",
		Vuid:   req.EcardNo,
	}
	reqSm4 := &models.Sm4EncryptReq{
		Info:  *sm4Info,
		Token: token,
	}
	sm4resp, err := helper.Sm4Encrypto(reqSm4)
	encryToken, err := helper.Sm2Encrypto(token, constant.CardCenterPubKey)
	ecardPa := &models.EcardPa{
		EncType:    "sm4",
		Method:     "query",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: sm4resp,
		Digest:     encryToken,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	res, err := (&ECardService{}).GetEcardInfo(ecardPa)
	// 如果卡管中心报错，直接院内建卡
	if err != nil {
		middlewares.Logger.Println("卡管中心报错------", err.Error())
		fmt.Println("如果卡管中心报错，直接院内建卡")
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	EcardInfo := res.RespData.BizContent
	fmt.Println("EcardInfo====", EcardInfo)

	Sm4DecryptReq := &models.Sm4DecryptReq{
		Token: token,
		Biz:   EcardInfo,
	}
	sm4DC, err := helper.Sm4Decrypto(Sm4DecryptReq)
	fmt.Println("sm4DC====", sm4DC)
	sss := &models.EcardInfoResp{}
	err = json.Unmarshal([]byte(sm4DC.RespData), sss)
	middlewares.Logger.Println("FindPatientCard====", sss)

	//2.判断是否已经建卡
	card, has, err := (&models.CardModel{}).FindCardByIDM(sss.People.IdNo)
	middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", card)
	if err != nil {
		middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", err)
		return err
	}
	//如果存在，直接绑卡
	//1. 查询是否已绑卡
	_, hasBind, err := (&models.CardModel{}).FindBindCardInfo(card.Id, req.Unionid)
	if hasBind {
		return fmt.Errorf("此卡已绑定在当前用户")
	}
	if has && !hasBind {
		reqCardBind := &models.CardBindModel{
			Unionid:   req.Unionid,
			PatientId: card.Id,
			Status:    1,
		}
		err = (&models.CardModel{}).BindCard(reqCardBind)
		return err
	}

	//检查卡是否在his系统
	reqFindCard := &models.Req3013Params{
		IDType:      "01",
		IDNo:        sss.People.IdNo,
		PatientName: sss.People.Name,
		PatientCard: sss.Vuid,
	}
	middlewares.Logger.Println("建卡建卡 卡管中心号码====", sss)
	middlewares.Logger.Println("建卡建卡 卡管中心号码====", reqFindCard)
	respFindPC, err := (&HisService{}).FindPatientCard(reqFindCard)
	middlewares.Logger.Println("FindPatientCard====", respFindPC)
	if respFindPC.ResultCode != "0" && respFindPC.ResultContent != "已存在同种类型的卡,不能发卡" && respFindPC.ResultContent != "此卡号已建卡." {
		return fmt.Errorf(respFindPC.ResultContent)
	}

	// 卡在his存在，直接绑
	if respFindPC.ResultCode == "-51" && respFindPC.ResultContent == "已存在同种类型的卡,不能发卡" {
		sex := sss.People.Gender
		sexint, err := strconv.Atoi(sex)
		if err != nil {
			middlewares.Logger.Println("CreateCard sexint failed ", err)
			return err
		}
		cmi := &models.CardModel{
			Age:        req.Age,
			CardNo:     "",
			EcardNo:    sss.Vuid,
			Empi:       "",
			IdNo:       sss.People.IdNo,
			Mobile:     req.Mobile,
			Nation:     req.Nation,
			RealName:   sss.People.Name,
			Sex:        sexint,
			SourceId:   respFindPC.PatientID,
			Occupation: "",
			CreatedAt:  cmn.JsonTime{},
			UpdatedAt:  cmn.JsonTime{},
		}
		cardN, err := (&models.CardModel{}).Insert(cmi)
		cardbindreq := &models.CardBindModel{
			Unionid:   req.Unionid,
			PatientId: cardN.Id,
			Status:    1,
		}
		err = (&models.CardModel{}).BindCard(cardbindreq)
		return nil
	}

	if len(sss.Vuid) != 64 {
		middlewares.Logger.Println("绑卡失败（电子健康卡数据错误）====", sss)
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	formatDob := sss.People.Birthday[0:4] + "-" + sss.People.Birthday[4:6] + "-" + sss.People.Birthday[6:8]
	fmt.Println(formatDob)
	sex := "1"
	if req.Sex == "女" {
		sex = "2"
	}
	bindCardReq := &models.Req3014Params{
		IDType:        "01",
		IDNo:          sss.People.IdNo,
		PatientName:   sss.People.Name,
		PatientCard:   sss.Vuid,
		Sex:           sex,
		DOB:           formatDob,
		Mobile:        req.Mobile,
		MaritalStatus: "",
		Address:       "",
		ContactTelNo:  "",
		ContactName:   "",
		ContactIDNo:   "",
	}
	bindRes, err := (&HisService{}).SavePatientCard(bindCardReq)
	patientId := ""
	if bindRes.ResultCode == "0" || bindRes.ResultCode == "-50" || bindRes.ResultCode == "-51" {
		patientId = bindRes.PatientId
	} else {
		return fmt.Errorf("建卡失败")
	}
	sexint, err := strconv.Atoi(sex)
	cmi := &models.CardModel{
		Age:        helper.GetAgeByBirthday(sss.People.IdNo),
		CardNo:     "",
		EcardNo:    sss.Vuid,
		Empi:       sss.Empi,
		IdNo:       sss.People.IdNo,
		Mobile:     "",
		Nation:     req.Nation,
		RealName:   sss.People.Name,
		Sex:        sexint,
		SourceId:   patientId,
		Occupation: req.Job,
		CreatedAt:  cmn.JsonTime{},
		UpdatedAt:  cmn.JsonTime{},
	}
	card, err = (&models.CardModel{}).Insert(cmi)
	if err != nil {
		return err
	}
	cardbindreq := &models.CardBindModel{
		Unionid:   req.Unionid,
		PatientId: card.Id,
		Status:    1,
	}
	err = (&models.CardModel{}).BindCard(cardbindreq)
	return nil
}

// Create
//
//	@Description: 建电子健康卡天府市民云
//	@receiver pc
//	@param req
//	@return error
func (pc *PatientCardService) CreateCardTf(req *models.EcardCreateReq) error {
	//2.判断是否已经建卡
	card, has, err := (&models.CardModel{}).FindCardByIDM(req.IdNo)
	middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", card)
	if err != nil {
		middlewares.Logger.Println("CreateCard FindCardsByUnionid failed ", err)
		return err
	}
	if has {
		return nil
	}

	secret, err := helper.Sm2Encrypto(constant.CardCenterAppSecret, constant.CardCenterPubKey)
	fmt.Println(secret)
	type BizContent struct {
		Secret string `json:"secret"`
	}
	biz := &BizContent{Secret: secret}
	ca := &models.Ca{
		EncType:    "SM4",
		Method:     "token",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: *biz,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	token, err := (&ECardService{}).GetToken(ca)
	// 不存在，就走卡管中心，建卡
	sm4Info := &models.Sm4Info{
		AppMode:       "6",
		IdType:        "01",
		IdNo:          req.IdNo,
		Klx:           "1",
		Name:          req.PatientName,
		Birthday:      req.Dob,
		Cellphone:     req.Mobile,
		Citizenship:   "1",
		EthnicityCode: "01",
		Gender:        "",
		HjAddress:     "地址2",
		NativePlace:   "地址3",
		Sbkh:          "333333",
		Telephone:     req.Mobile,
		TerminalType:  "1",
		Unit:          "地址3",
		Ylfyzffs:      "01",
		Zydm:          "8",
		Rzfs:          "05",
	}
	reqSm4 := &models.Sm4EncryptReq{
		Info:  *sm4Info,
		Token: token,
	}
	sm4resp, err := helper.Sm4Encrypto(reqSm4)
	encryToken, err := helper.Sm2Encrypto(token, constant.CardCenterPubKey)
	ecardPa := &models.EcardPa{
		EncType:    "sm4",
		Method:     "regquery",
		DigestType: "SM2",
		AppId:      "fbb60a68e8c7490da216c9eeddf09abd",
		BizContent: sm4resp,
		Digest:     encryToken,
		Version:    "v1.10",
		Timestamp:  time.Now().UnixMicro(),
	}
	fmt.Println(ecardPa)
	res, err := (&ECardService{}).GetEcard(ecardPa)
	// 如果卡管中心报错，直接院内建卡
	if err != nil {
		middlewares.Logger.Println("卡管中心报错------", err.Error())
		fmt.Println("如果卡管中心报错，直接院内建卡")
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	EcardInfo := res.RespData.BizContent
	fmt.Println("EcardInfo====", EcardInfo)

	Sm4DecryptReq := &models.Sm4DecryptReq{
		Token: token,
		Biz:   EcardInfo,
	}
	sm4DC, err := helper.Sm4Decrypto(Sm4DecryptReq)

	type Sm4DCModel struct {
		EcContent string `json:"ecContent"`
		Vuid      string `json:"vuid"`
		Empi      string `json:"empi"`
	}
	sss := &Sm4DCModel{}
	err = json.Unmarshal([]byte(sm4DC.RespData), sss)
	middlewares.Logger.Println("FindPatientCard====", sss)
	//检查卡是否在his系统
	reqFindCard := &models.Req3013Params{
		IDType:      "01",
		IDNo:        req.IdNo,
		PatientName: req.PatientName,
		PatientCard: sss.Vuid,
	}
	respFindPC, err := (&HisService{}).FindPatientCard(reqFindCard)
	if respFindPC.ResultCode != "0" && respFindPC.ResultContent != "已存在同种类型的卡,不能发卡" && respFindPC.ResultContent != "此卡号已建卡." {
		return fmt.Errorf(respFindPC.ResultContent)
	}

	// 卡在his存在，直接绑
	if respFindPC.ResultCode == "-51" && respFindPC.ResultContent == "已存在同种类型的卡,不能发卡" && respFindPC.ResultContent != "此卡号已建卡." {
		sex := "1"
		if req.Sex == "女" {
			sex = "2"
		}
		sexint, err := strconv.Atoi(sex)
		if err != nil {
			middlewares.Logger.Println("CreateCard sexint failed ", err)
			return err
		}
		cmi := &models.CardModel{
			Age:        req.Age,
			CardNo:     "",
			EcardNo:    respFindPC.PatientCard,
			Empi:       "",
			IdNo:       req.IdNo,
			Mobile:     req.Mobile,
			Nation:     req.Nation,
			RealName:   req.PatientName,
			Sex:        sexint,
			SourceId:   respFindPC.PatientID,
			Occupation: req.Job,
			CreatedAt:  cmn.JsonTime{},
			UpdatedAt:  cmn.JsonTime{},
		}
		_, err = (&models.CardModel{}).Insert(cmi)
		return nil
	}

	if len(sss.Vuid) != 64 {
		middlewares.Logger.Println("绑卡失败（电子健康卡数据错误）====", sss)
		errHosp := pc.CreateHospCard(req)
		return errHosp
	}
	formatDob := req.Dob[0:4] + "-" + req.Dob[4:6] + "-" + req.Dob[6:]
	fmt.Println("formatDob------------", formatDob)
	sex := "1"
	if req.Sex == "女" {
		sex = "2"
	}
	bindCardReq := &models.Req3014Params{
		IDType:        "01",
		IDNo:          req.IdNo,
		PatientName:   req.PatientName,
		PatientCard:   sss.Vuid,
		Sex:           sex,
		DOB:           formatDob,
		Mobile:        req.Mobile,
		MaritalStatus: req.MaritalStatus,
		Address:       req.Address,
		ContactTelNo:  req.ContactTelNo,
		ContactName:   req.ContactName,
		ContactIDNo:   req.ContactIDNo,
		Nation:        req.Nation,
		Occupation:    req.Job,
	}
	bindRes, err := (&HisService{}).SavePatientCard(bindCardReq)
	fmt.Println("bindRes:=======", bindRes)
	patientId := ""
	if bindRes.ResultCode == "0" || bindRes.ResultCode == "-50" || bindRes.ResultCode == "-51" {
		patientId = bindRes.PatientId
	} else {
		return fmt.Errorf("建卡失败")
	}
	sexint, err := strconv.Atoi(sex)
	fmt.Println("sexint----------", sexint)
	cmi := &models.CardModel{
		Age:        helper.GetAgeByBirthday(req.IdNo),
		CardNo:     "",
		EcardNo:    sss.Vuid,
		Empi:       sss.Empi,
		IdNo:       req.IdNo,
		Mobile:     req.Mobile,
		Nation:     req.Nation,
		RealName:   req.PatientName,
		Sex:        sexint,
		SourceId:   patientId,
		Occupation: req.Job,
		CreatedAt:  cmn.JsonTime{},
		UpdatedAt:  cmn.JsonTime{},
	}
	card, err = (&models.CardModel{}).Insert(cmi)
	return nil
}

func (pc *PatientCardService) GetAge(req *models.GetAge) (*models.CardModel, error) {
	sm := &models.CardModel{}
	data, err := sm.GetAge(req.PatientId)
	if len(data.IdNo) > 15 {
		data.Age = helper.GetAgeByBirthday(data.IdNo)
		data.IdNo = data.IdNo[0:3] + "***********" + data.IdNo[14:]
	}
	return data, err
}

func (pc *PatientCardService) BindBobo(req *models.CardModel) error {
	sm := &models.CardModel{}
	data, has, err := sm.GetPatientBySourceId(req.SourceId)
	if !has {
		return fmt.Errorf("登记号不存在")
	}
	err = sm.BindBobo(data.Id)
	if err != nil {
		return err
	}
	return err
}

func (pc *PatientCardService) Query(req *models.ReqCardQuery) ([]models.CardModel, int64, error) {
	data, total, err := (&models.CardModel{}).Query(req)
	if err != nil {
		return nil, 0, err
	}
	return data, total, nil
}

func (pc *PatientCardService) FindSourceId(req *models.CardModel) (*models.CardModel, error) {
	data, has, err := (&models.CardModel{}).FindByPatientId(req.SourceId)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, fmt.Errorf("患者不存在")
	}
	return data, nil
}
